<template>
    <div class="tabsbread">
        <!-- 标签页 面包屑导航 -->
        <ul class="tabsbread-ul">
            <li
                v-for="(item, index) in tabsData" :key="index" 
                :class="[item.label === currentPage ? 'active-tab-item' : '', 'tabs-item']"
                @click="tabsbreadClickChange(item)"
            >
                <p :title="item.label" class="tabsbread-listname">{{item.label}}</p>
                <span class="close" @click.stop="removeTabs(item)" />
            </li>
        </ul>

    </div>
</template>

<script>
import route from '@/router';
import { mapActions } from 'vuex';
export default {
    name: 'tabsbread',
    components:{
        
    },
    data () {
        return {
        currentPage: '',
        tabsData: []
        }
    },
    computed: {
        lang () {
        return this.$t('lang')
        }
    },
    mounted(){
        
    },
    methods: {
        ...mapActions('qxz', [
            'updateOpeningPages'
        ]),
        // 点击切换页面
        tabsbreadClickChange (item) {
            item.path && this.$router.push({path: item.historyPath})
        },
        // 当前的路由的子模块
        getModule() {
            let temp, path = this.$route.path;
            let moduleName = path.split('/')[1]
            moduleName && route.options.routes.map(ele => {
                if(moduleName === ele.name) {
                    temp = ele
                }
            })
            return temp
        },
        // 关闭
        removeTabs(item) {
            // 只剩一个了，先不关了
            if(this.tabsData.length === 1) {
                return
            }
            // cache clean (hack)
            try{
                this.$route.matched[1].instances.default.$vnode.parent.componentInstance.cache = {}
            }catch(err) {
                console.log('cache clean failed', err)
            }
            let arr = [], ind;
            // 删掉关闭的
            this.tabsData.map((ele, index) => {
                if(ele.label === item.label){
                    ind = index
                }else {
                    arr.push(ele)
                }
            })
            // 如果关闭的是现在打开的
            if(item.label === this.currentPage) {
                if(ind > 0) {
                    this.tabsbreadClickChange(arr[ind - 1])
                }else {
                    this.tabsbreadClickChange(arr[ind])
                }
            }
            this.tabsData = arr;
            // 已经打开的tabs存到vuex供左侧列表判断跳转路由时使用
            this.$nextTick(() => {
                this.updateOpeningPages(this.tabsData)
            })
        },
        addTab(item) {
            let opened = false;
            this.currentPage = item.label;
            // 加上参数
            let query = this.$route.query;
            let str = ''
            for(let key in query) {
                str += `${key}=${query[key]}&`
            }
            str && (str = str.substr(0, str.length - 1))
            item.historyPath = `/${item.module}/${item.path}${str ? '?' : ''}${str}`
            
            // 已经有,切换&高亮显示
            this.tabsData.map((ele, index) => {
                if(ele.label === item.label) {
                    opened = true;
                    this.currentPage = item.label
                    // 替换原有项,因为这次可能是跳转子页面
                    this.tabsData.splice(index, 1, item)
                }
            })
            // 没有或者不包含这一项,添加
            if(this.tabsData.length === 0 || !opened) {
                this.tabsData.push(item)
            }
            // 已经打开的tabs存到vuex供左侧列表判断跳转路由时使用
            this.$nextTick(() => {
                this.updateOpeningPages(this.tabsData)
            })
        }
    },
    watch: {
        $route: {
            immediate:true,
            handler: function (newVal, oldVal) {
                let accessDenied = false
                let modules = this.getModule()
                let listConfig = localStorage.getItem('menuInfoList') ? JSON.parse(localStorage.getItem('menuInfoList')) : '';
                if(!Array.isArray(listConfig) || listConfig.length === 0) {
                    return
                }
                // 权限列表的当前模块
                let matchedModule = listConfig.filter(ele => {
                    return (ele.menu_url === modules.name && ele.parent_id === 200)
                });
                // 2级菜单
                let secArr = []
                listConfig.forEach(ele => {
                    if(ele.parent_id === matchedModule[0].id) {
                        secArr.push(ele)
                    }
                })
                // 3级菜单
                let thirdArr = []
                listConfig.forEach(ele => {
                    secArr.forEach(item => {
                        if(item.id === ele.parent_id) {
                            ele.parent_name = item.menu_name
                            thirdArr.push(ele)
                        }
                    })
                })
                if(modules && modules.children) {
                    modules.children.map((ele, index) => {
                        if(!ele.redirect) {
                            // 没有权限的页面，提示后跳回去
                            thirdArr.forEach(item => {
                                if(item.menu_name === ele.label && item.parent_name === ele.className) {
                                    if(ele.name === newVal.name) {
                                        accessDenied = true
                                    }
                                }
                            })
                        }
                    })
                }
                if(newVal.matched.length) {
                    let previousModule = oldVal ? oldVal.path.split('/')[1] : ''
                    let currentModule = newVal.matched[0].path.split('/')[1]
                    // 切换了模块,清空tabs
                    if(previousModule !== currentModule) {
                        this.tabsData = []
                    }
                    route.options.routes.map(ele => {
                        if(ele.path === newVal.matched[0].path) {
                            let isOpen = false;
                            Array.isArray(ele.children) && ele.children.map(item =>{
                                if(item.name === newVal.name) {
                                    // 没有权限的页面，不添加
                                    thirdArr.forEach(element => {
                                        if(element.menu_name === item.label && element.parent_name === item.className) {
                                            isOpen = true
                                            this.addTab(item);
                                        }
                                    })
                                }
                            })
                            // 没有这个路由
                            if(!isOpen) {
                                this.tabsData = []
                                // throw new TypeError('router config required')
                            }
                        }
                    })
                }else {
                    // 这个模块没有匹配到子路由或者有问题
                    this.tabsData = []
                    throw new TypeError('tabsbread compile error')
                }
            }
        }
    },
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .tabsbread{
    width: 100%;
  }
  .tabsbread-ul{
    width: 100%;
    height: 40px;
    display: flex;
    background-color: #e9e9e9;
  }
  .tabsbread-ul .tabs-item{
    border-right: 1px solid #e9e9e9;
    border-bottom: 1px solid #e9e9e9;
    box-sizing: border-box;
    display: flex;
    max-width: 180px;
    justify-content: center;
    align-items: center;
    font-family: "Microsoft YaHei","微软雅黑","Microsoft JhengHei","华文细黑",STHeiti,MingLiu,'Avenir', Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #7e6b5a;
    padding: 0 24px;
    cursor: pointer;
    background-color: #dddddd;
    overflow: hidden;
    /* flex: 1; */
  }
  .tabsbread-ul .tabs-item .tabsbread-listname{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .tabsbread-ul .tabs-item .close{
    width: 12px;
    height: 12px;
    margin-left: 15px;
    background: url('../../assets/img/form_close_normal.png') center center/100% 100% no-repeat;
  }
  .tabsbread-ul .tabs-item .close:hover{
    background: url('../../assets/img/form_close_selected.png') center center/100% 100% no-repeat;
  }
  .tabsbread-ul .tabs-item .close img{
    display: block;
    width: 100%;
    height: 100%;
  }
  .tabsbread-ul .active-tab-item{
    background-color: #fff;
	border-right: none;
  }
  .bread-nav{
    width: 100%;
    height: 48px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-left: 25px;
    box-sizing: border-box;
    font-family: "Microsoft YaHei","微软雅黑","Microsoft JhengHei","华文细黑",STHeiti,MingLiu,'Avenir', Helvetica, Arial, sans-serif;
    font-size: 16px;
    color: #888888;
  }
</style>
